#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "./build.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

if [[ ! "$1" =~ ^/.* || "$1" = "/" ]]; then echo "请输入正确的构建路径"; exit 1; fi
if [[ ! "$2" =~ ^/.* || "$2" = "/" ]]; then echo "请输入正确的安装路径"; exit 1; fi

create_dir()
{
    local path=$1
    [[ "$path" =~ .*/$ ]] && path=${path%/*}
    if [[ ! -d "$path" && ! -f "$path" ]]; then mkdir -p $path; else path=$path`date "+%y%m%d%H%M%S"` && mkdir -p $path; fi
    echo $path
}

buildpath=$(create_dir $1)
installpath=$(create_dir $2)

yum install -y wget tar environment-modules
source /etc/profile
module purge

set -e
dep_dir="dependency"
#毕昇编译器安装
bash $dep_dir/bisheng-compiler-2.1.0.sh $buildpath $installpath
module use $installpath/bisheng-compiler-2.1.0
module load $installpath/bisheng-compiler-2.1.0/bisheng_modulefiles
#lastz安装
bash $dep_dir/lastz.sh $buildpath $installpath
module use $installpath/lastz-distrib
module load $installpath/lastz-distrib/lastz_modulefiles
#3d-dna安装
bash 3d-dna-master.sh $buildpath $installpath
module use $installpath/3d-dna
module load $installpath/3d-dna/3d-dna_modulefiles

mkdir -p pkg/3d-dna-master-hpc && cp -r $installpath/* pkg/3d-dna-master-hpc/
cat>"pkg/3d-dna-master-hpc/run.sh"<<EOF
yum install -y wget tar environment-modules java-1.8.0-openjdk python3 python3-matplotlib python3-numpy python3-scipy
pwd_path=\$('pwd')
current_dir=\$(cd "\$(dirname "\${BASH_SOURCE[0]}")" &> /dev/null && pwd)
for d in \$(ls \$current_dir)
do
    [ ! -f "\$current_dir/\$d" ] && cd \$current_dir/\$d && module use \$(pwd) && module load \$(pwd)/*modulefiles
done
cd \$pwd_path
EOF
cd pkg/ && tar zcvf 3d-dna-master-hpc.tar.gz 3d-dna-master-hpc

rm -rf $buildpath $installpath
